/*常量*/
var CONSTANT = {
	DATA_TABLES : {
		DEFAULT_OPTION : { // DataTables初始化选项
			"processing" : true, // 隐藏加载提示,自行处理
			"bServerSide" : true,
			"bStateSave" : true,
			"bFilter" : false,// 去掉搜索框// sort, etc) in
			"searching" : false,// 禁用表格内搜索
			"lengthMenu" : [ 3, 5, 10 ],
			"pageLength" : 5,
			"displayLength" : 5,
			'autoWidth' : true,
			"bSort" : false,
			"language" : {
				"processing" : "处理中...",
				"lengthMenu" : "每页 _MENU_ 项",
				"zeroRecords" : "没有匹配结果",
				"info" : "总共_PAGES_ 页，显示第_START_ 到第 _END_ ，筛选之后得到 _TOTAL_ 条，初始_MAX_ 条 ",
				"infoEmpty" : "当前显示第 0 至 0 项，共 0 项",
				"infoFiltered" : "(由 _MAX_ 项结果过滤)",
				"infoPostFix" : "",
				"search" : "搜索:",
				"url" : "",
				"emptyTable" : "表中数据为空",
				"loadingRecords" : "载入中...",
				"infoThousands" : ",",
				"paginate" : {// 分页的样式文本内容。
					"previous" : "上一页",
					"next" : "下一页",
					"first" : "第一页",
					"last" : "最后一页",
					"jump" : "跳转",
				},
				"aria" : {
					"sortAscending" : ": 以升序排列此列",
					"sortDescending" : ": 以降序排列此列"
				}
			}

		},
		CELL_CHECKBOX : { // 复选框单元格
			// 复选框单元格
			"className" : "td-checkbox",
			"orderable" : false,
			"data" : "id",
			"width" : "30px",
			"render" : function(data, type, row, meta) {
				return '<input type="checkbox" value=' + data
						+ ' class="iCheck">';
			}
		}

	}
};

var curtable;
$(document)
		.ready(
				function() {
					var table = $('#menuTable');
					curtable = table
							.DataTable($
									.extend(
											{ // old API: $().dataTable()
												// returns jQuery object, so you
												// should use .api() in order to
												// use DataTable API methods:
												// oTable.api().ajax.reload();
												// "order": [ 3, "desc" ],
												"ajax" : {
													url : basePath
															+ "/sys/menu/ajaxGetListPageMenu.shtml",
													type : "post",
													contentType : "application/json; charset=UTF-8",
													dataType : "json",
													"data" : function(d) {
														return JSON
																.stringify(getQueryCondition(d));
													},
													"dataSrc" : function(
															returnData) {
														returnData.sEcho = returnData.draw + 1;
														if (returnData.msg) {
															returnData.data = "";
															return returnData.data;
														}
														return returnData.data;
													},
													error : function(xhr) {
														alert("服务出错!");
													}
												},

												/*
												 * "fnServerParams": function (
												 * data ) { return
												 * JSON.stringify(getQueryCondition(data)) ; },
												 */
												/*
												 * function(data, callback) {
												 * $.ajax({ url : basePath +
												 * "/sys/menu/ajaxGetListPageMenu.shtml",
												 * type : "post", data :
												 * JSON.stringify(getQueryCondition(data)),
												 * contentType :
												 * "application/json;
												 * charset=UTF-8", dataType :
												 * "json", success :
												 * function(jsonResult) { if
												 * (jsonResult.success) { //
												 * 封装返回数据，这里仅演示了修改属性名 var
												 * returnData = {}; //
												 * returnData.draw // =8;// //
												 * data.draw;//这里直接自行返回了draw计数器,应该由后台返回
												 * returnData.iTotalDisplayRecords =
												 * jsonResult.totalCount; //
												 * returnData.sEcho=2;
												 * returnData.data =
												 * jsonResult.data;
												 * returnData.iTotalRecords =
												 * jsonResult.totalCount;
												 * 
												 * callback(returnData);
												 *  } else { Metronic .alert({
												 * type : (jsonResult.success ==
												 * true ? 'success' : 'danger'),
												 * icon : (jsonResult.success ==
												 * true ? 'check' : 'warning'),
												 * message :
												 * jsonResult.errorMessages[0].msg,
												 * container : tableWrapper,
												 * place : 'prepend' });
												 * 
												 * //curtable.Table.Rows.Clear() //
												 * curtable.Rows.Clear(); var
												 * returnData = {}; //
												 * returnData.draw // =8;// //
												 * data.draw;//这里直接自行返回了draw计数器,应该由后台返回
												 * returnData.iTotalDisplayRecords
												 * =0;// jsonResult.totalCount; //
												 * returnData.sEcho=2;
												 * returnData.data ="";//
												 * jsonResult.data;
												 * returnData.iTotalRecords =
												 * 0;//jsonResult.totalCount;
												 * callback(returnData); } }, //
												 * 请求失败 error : function(xhr) {
												 *  } }); },
												 */
												"columns" : [
														{ // 复选框单元格
															"className" : "td-checkbox",
															"data" : "id",
															"orderable" : false,
															"width" : "30px",
															"render" : function(
																	data, type,
																	row, meta) {
																return '<input type="checkbox" value='
																		+ data
																		+ ' class="iCheck group-checkable  " data-set>';
															}
														},
														{
															"data" : "name",
															"name" : "name",
															"width" : "130px",
															"orderable" : false
														},
														{
															"data" : "pid",
															"name" : "pid",
															"orderable" : false
														},
														{
															"data" : "permission",
															"name" : "permission",
															"orderable" : false
														},
														{
															"data" : "lev",
															"name" : "lev",
															"orderable" : false
														},
														{
															"data" : "href",
															"name" : "href",
															"width" : "50px",
															"orderable" : false
														},
														{
															"data" : "icon",
															"name" : "icon",
															"orderable" : false,
															render : function(
																	data, type,
																	row, meta) {
																return '<i  class='
																		+ data
																		+ '></i>';
															}
														},
														{
															"data" : null,
															"width" : "80px",
															"defaultContent" : "",
															"orderable" : false
														} ],
												// 在最后一列增加编辑删除按钮
												"createdRow" : function(row,
														data, index) {
													// 行渲染回调,在这里可以对该行dom元素进行任何操作
													$('td', row).eq(7)
															.addClass("taC");
													var btnEdit = $('<div class="userM-table-function"><a id="btnEdit" class="fa fa-pencil-square text-success"></a> <a id="btnDel" class="fa fa-trash text-danger"></a></div>');
													$('td', row).eq(7).append(
															btnEdit);
												}
											},
											CONSTANT.DATA_TABLES.DEFAULT_OPTION));

					var tableWrapper = jQuery('#menuTable_wrapper');
			
					  $('.group-checkable').change(function() {
							var set = jQuery(this).attr("data-set");
							var checked = jQuery(this).is(":checked");
							jQuery(".iCheck").each(function() {
								if (checked) {
									$(this).attr("checked", true);
									$(this).parents('tr').addClass("active");
								} else {
									$(this).attr("checked", false);
									$(this).parents('tr').removeClass("active");
								}
							});
							jQuery.uniform.update(set);
						});
					tableWrapper.on('change', 'tbody tr .checkboxes', function() {
						$(this).parents('tr').toggleClass("active");
					});

					$('.dataTables_length select').addClass(
							"form-control input-xsmall input-inline"); // modify
					// table
					// per

					// 获取点击事件
					$('#roleTree').bind("activate_node.jstree",
							function(obj, e) {
								// 处理代码
								// 获取当前节点
								currentNode = e.node;
								$("#curSelNodeId").val(currentNode.id);
								$("#curSelNodeName").val(currentNode.text);
								
								// curtable.api().ajax.reload();// 1.10版本之前的
								// $().dataTable() (v1.9 and earlier)
								curtable.ajax.reload();
							})
					//新增数据
                   $('#btnAddMenu').on('click', function() {
                	   $("#parentName").val($("#curSelNodeName").val());
                   });
					// 数据删除
					$('#menuTable tbody').on('click', 'A#btnEdit', function() {
						var data = curtable.row($(this).parents('tr')).data();
						alert(data);
						/*
						 * $.ajax({ url: 'deltable', type: 'POST', dataType:
						 * 'json', data: {id: data[0]}, }) .done(function(data) {
						 * if (data=="success") { tables.ajax.reload(); }; })
						 * .fail(function() { alert("error"); });
						 */
					});
					// 数据编辑
					$('#menuTable tbody').on('click', 'A#btnDel', function() {
						var data = curtable.row($(this).parents('tr')).data();
						alert(data);
						/*
						 * var fields = $("#add-form").serializeArray();
						 * jQuery.each( fields, function(i, field){
						 * //jquery根据name属性查找
						 * $(":input[name='"+field.name+"']").val(data[i]); });
						 * $(":input[name='mark']").val("edit");
						 * $("#modal-form").modal("show");//弹出框show
						 */
					});
					//查询
					$("#btnSearch").click(function() {
						curtable.ajax.reload();
					});
					$('#spinner').spinner();
				})

function getQueryCondition(data) {
	// var param = {};
	// 组装排序参数
	/*
	 * if (data.order&&data.order.length&&data.order[0]) { switch
	 * (data.order[0].column) { case 1: param.orderColumn = "name"; break; case
	 * 2: param.orderColumn = "position"; break; case 3: param.orderColumn =
	 * "status"; break; case 4: param.orderColumn = "start_date"; break;
	 * default: param.orderColumn = "name"; break; } param.orderDir =
	 * data.order[0].dir; }
	 */
	// 组装查询参数
	// param.fuzzySearch = userManage.fuzzySearch;
	/*
	 * if (userManage.fuzzySearch) { param.fuzzy = $("#fuzzy-search").val();
	 * }else{ param.name = $("#name-search").val(); param.position =
	 * $("#position-search").val(); param.office = $("#office-search").val();
	 * param.extn = $("#extn-search").val(); param.status =
	 * $("#status-search").val(); param.role = $("#role-search").val(); }
	 */
	// 组装分页参数
	data.STARTINDEX = data.start;
	data.PAGESIZE = data.length;
	data.pid = $("#curSelNodeId").val();
	data.permission = $("#permission").val();
	data.name = $("#name").val();
	data.sEcho = data.draw;
	return data;
}
